package com.moonbeom.pptimer;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class TimeThread extends Thread{
	final int FINISH = -1;

	boolean isRun;
	boolean isWorking;

	long standardTime;
	int second;

	int nowSlide;
	int numSlide;
	int alarmTime;

	Handler tHandler;
	Message toActivity;

	TextView infoText;

	public void setInfoText(TextView infoText){

		if(infoText != null){
			this.infoText = infoText;
		}

		else{
			Log.d("Error", "Not Found TextView");
		}
	}

	public void setTime(int numSlide, int alarmTime){
		this.nowSlide = 1;

		this.standardTime = System.currentTimeMillis();
		this.numSlide = numSlide;
		this.alarmTime = alarmTime;
	}

	public void setRun(boolean isRun){
		this.isRun = isRun;
	}

	public void setWorking(boolean isWorking){
		this.isWorking = isWorking;
	}

	public void setHandler(Handler tHandler){
		this.tHandler = tHandler;
	}


	public void run() {
		// TODO Auto-generated method stub
		this.isRun = true;
		this.isWorking = true;

		Looper.prepare();

		while(isRun){
			if(isWorking){
				second = (int) (System.currentTimeMillis() - this.standardTime)/1000;



				if(second > this.alarmTime){
					second = 0;
					nowSlide++;
					this.standardTime = System.currentTimeMillis();
				}

				if(numSlide < nowSlide){
					second = 0;
					nowSlide = 0;
					isWorking = false;
				}

				synchronized (tHandler) {
					toActivity = tHandler.obtainMessage();

					if(isWorking){
						toActivity.arg1 = nowSlide;
						toActivity.arg2 = second;
					}

					else{
						toActivity.arg1 = FINISH;
					}

					tHandler.sendMessage(toActivity);
				}

				try {
					TimeThread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			else{
				try {
					TimeThread.sleep(300);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		Looper.loop();
	}

}
